-- Script/SceneManager.lua
local Director = require("Director")
local DisplayConfig = require("Script.DisplayConfig")
local Vec2 = require("Vec2")
local Rect = require("Rect")
local SceneConfig = require("Script.SceneConfig")

local SceneManager = {}
SceneManager.__index = SceneManager

function SceneManager.new()
    local instance = {
        scenes = {},
        currentScene = nil,
        currentSceneName = nil,
        sceneStack = {}
    }
    
    return setmetatable(instance, SceneManager)
end

-- 智能相机设置方法
function SceneManager:setupSceneCamera(scene, targetNode, sceneType)
    if not scene or not scene.camera then 
        print("警告：场景或相机不存在")
        return 
    end
    
    -- 获取相机边界配置 - 使用世界边界而不是相机边界
    local worldBounds = DisplayConfig.WORLD_BOUNDS
    local cameraBounds = DisplayConfig.getCameraBounds()
    
    -- 设置相机边界为整个世界的边界
    scene.camera.boundary = Rect(
        worldBounds.left, 
        worldBounds.bottom, 
        worldBounds.width, 
        worldBounds.height
    )
    
    -- 设置相机缩放 - 保持原始缩放，不跟随角色缩小
    scene.camera.zoom = 1.0  -- 改为固定值1.0，保持原始大小
    
    -- 根据场景类型设置不同的跟随参数
    if sceneType == "wide" then
        -- 宽场景：水平跟随更慢，垂直跟随正常
        scene.camera.followRatio = Vec2(0.5, 0.5)
    else
        -- 正常场景：标准跟随
        scene.camera.followRatio = Vec2(0.5, 0.5)
    end
    
    -- 设置跟随目标
    if targetNode then
        scene.camera.followTarget = targetNode
        print("设置相机跟随目标")
    end
    
    print("相机设置完成，缩放: 1.0 (固定)")
end

-- 自动设置相机
function SceneManager:autoSetupCamera(scene)
    if not scene or not scene.camera then 
        print("警告：无法自动设置相机，场景或相机不存在")
        return 
    end
    
    -- 检测场景宽高比
    local worldBounds = DisplayConfig.WORLD_BOUNDS
    local sceneAspect = worldBounds.width / worldBounds.height
    local targetAspect = DisplayConfig.TARGET_WIDTH / DisplayConfig.TARGET_HEIGHT
    
    -- 判断场景类型：宽场景或正常场景
    local sceneType = (sceneAspect > targetAspect * 1.5) and "wide" or "normal"
    
    -- 设置基础相机参数
    self:setupSceneCamera(scene, nil, sceneType)
end

-- 设置场景的相机跟随目标
function SceneManager:setCameraTarget(scene, targetNode)
    if not scene or not targetNode then 
        print("警告：无法设置相机目标，场景或目标节点不存在")
        return 
    end
    
    -- 检测场景类型
    local worldBounds = DisplayConfig.WORLD_BOUNDS
    local sceneAspect = worldBounds.width / worldBounds.height
    local targetAspect = DisplayConfig.TARGET_WIDTH / DisplayConfig.TARGET_HEIGHT
    
    -- 判断场景类型
    local sceneType = (sceneAspect > targetAspect * 1.5) and "wide" or "normal"
    
    -- 重新设置相机参数（包含目标）
    self:setupSceneCamera(scene, targetNode, sceneType)
end

-- 注册场景
function SceneManager:registerScene(name, creatorFunc)
    self.scenes[name] = creatorFunc
    print("注册场景: " .. name)
end

-- 切换到下一个场景
function SceneManager:switchToNextScene()
    local currentSceneId = self.currentSceneName
    local nextSceneId = SceneConfig.getNextSceneId(currentSceneId)
    
    print("尝试切换到下一个场景，当前: " .. (currentSceneId or "nil") .. ", 下一个: " .. (nextSceneId or "nil"))
    
    if nextSceneId then
        return self:switchToScene(nextSceneId, { fromDirection = "left" })
    end
    return false
end

-- 切换到上一个场景
function SceneManager:switchToPrevScene()
    local currentSceneId = self.currentSceneName
    local prevSceneId = SceneConfig.getPrevSceneId(currentSceneId)
    
    print("尝试切换到上一个场景，当前: " .. (currentSceneId or "nil") .. ", 上一个: " .. (prevSceneId or "nil"))
    
    if prevSceneId then
        return self:switchToScene(prevSceneId, { fromDirection = "right" })
    end
    return false
end

-- 增强的切换场景方法，支持方向参数
function SceneManager:switchToScene(name, transitionData)
    print("=== 开始场景切换 ===")
    print("目标场景: " .. (name or "nil"))
    print("当前场景: " .. (self.currentSceneName or "nil"))
    
    if not self.scenes[name] then
        print("错误：场景未注册: " .. name)
        print("已注册的场景: " .. table.concat(self:getSceneList(), ", "))
        return false
    end
    
    transitionData = transitionData or {}
    
    -- 移除当前场景
    if self.currentScene and self.currentScene.parent then
        print("移除当前场景: " .. (self.currentSceneName or "未知"))
        self.currentScene:removeFromParent()
    end
    self.currentScene = nil
    self.currentSceneName = nil
    
    -- 创建新场景
    print("创建新场景: " .. name)
    local newScene = self.scenes[name](transitionData)
    if newScene then
        self.currentScene = newScene
        self.currentSceneName = name
        
        -- 自动设置相机参数
        self:autoSetupCamera(newScene)
        
        -- 将场景添加到Director入口
        if Director.entry and not newScene.parent then
            Director.entry:addChild(newScene)
            print("场景添加到Director入口")
        else
            print("警告：场景已存在父节点或Director.entry不存在")
        end
        
        -- 触发场景切换事件
        self:onSceneChanged(name, transitionData)
        
        print("=== 场景切换完成 ===")
        return true
    else
        print("错误：场景创建失败")
    end
    
    return false
end

-- 场景切换回调
function SceneManager:onSceneChanged(newSceneId, transitionData)
    print("场景切换到: " .. newSceneId)
    
    -- 这里可以添加场景切换的通用逻辑
    -- 比如播放音效、保存游戏状态等
end

-- 获取当前场景配置
function SceneManager:getCurrentSceneConfig()
    if self.currentSceneName then
        return SceneConfig.getSceneById(self.currentSceneName)
    end
    return nil
end

-- 检查是否可以切换到下一个场景
function SceneManager:canSwitchToNext()
    if self.currentSceneName then
        return SceneConfig.canGoNext(self.currentSceneName)
    end
    return false
end

-- 检查是否可以切换到上一个场景
function SceneManager:canSwitchToPrev()
    if self.currentSceneName then
        return SceneConfig.canGoPrev(self.currentSceneName)
    end
    return false
end

-- 推入场景（保留当前场景）
function SceneManager:pushScene(name, transitionData)
    if not self.scenes[name] then
        return false
    end
    
    -- 将当前场景加入堆栈
    if self.currentScene then
        table.insert(self.sceneStack, {
            scene = self.currentScene,
            name = self.currentSceneName
        })
        
        -- 隐藏当前场景但不移除
        self.currentScene.visible = false
    end
    
    -- 创建新场景
    local newScene = self.scenes[name](transitionData)
    if newScene then
        self.currentScene = newScene
        self.currentSceneName = name
        
        -- 自动设置相机参数
        self:autoSetupCamera(newScene)
        
        -- 将场景添加到Director入口
        if Director.entry and not newScene.parent then
            Director.entry:addChild(newScene)
        end
        
        return true
    end
    
    return false
end

-- 弹出场景（返回上一个场景）
function SceneManager:popScene()
    if #self.sceneStack == 0 then
        return false
    end
    
    -- 移除当前场景
    if self.currentScene and self.currentScene.parent then
        self.currentScene:removeFromParent()
    end
    self.currentScene = nil
    self.currentSceneName = nil
    
    -- 恢复上一个场景
    local previous = table.remove(self.sceneStack)
    self.currentScene = previous.scene
    self.currentSceneName = previous.name
    self.currentScene.visible = true
    
    return true
end

-- 获取当前场景
function SceneManager:getCurrentScene()
    return self.currentScene
end

-- 获取当前场景名称
function SceneManager:getCurrentSceneName()
    return self.currentSceneName
end

-- 检查场景是否存在
function SceneManager:hasScene(name)
    return self.scenes[name] ~= nil
end

-- 获取已注册的场景列表
function SceneManager:getSceneList()
    local list = {}
    for name, _ in pairs(self.scenes) do
        table.insert(list, name)
    end
    return list
end

-- 清理所有场景
function SceneManager:cleanup()
    -- 移除当前场景
    if self.currentScene and self.currentScene.parent then
        self.currentScene:removeFromParent()
    end
    
    -- 清理堆栈中的场景
    for _, sceneInfo in ipairs(self.sceneStack) do
        if sceneInfo.scene and sceneInfo.scene.parent then
            sceneInfo.scene:removeFromParent()
        end
    end
    
    -- 重置所有状态
    self.scenes = {}
    self.currentScene = nil
    self.currentSceneName = nil
    self.sceneStack = {}
end

return SceneManager